package com.tianhui.consignortwofei.mvp.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.DateUtil;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.google.gson.reflect.TypeToken;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.PointDateInfo;
import com.tianhui.consignortwofei.mvp.model.enty.TrajectoryInfo;
import com.tianhui.consignortwofei.mvp.model.enty.TrajectoryResultInfo;
import com.tianhui.consignortwofei.utils.Transform;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.resource.ResourceUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author fgs
 * @date 2020/9/28
 * @description
 **/
public class VehicleTrajectoryActivity extends BaseActivity {

    @BindView(R.id.layout_map_view_bd_mapView)
    MapView mMapView;
    private BaiduMap mBaiDuMap;
    private OrderModel mOrderModel;
    private OrderInfo orderInfo;

    @Override
    public int getLayoutId() {
        return R.layout.activity_vehicle_trajectory;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public String getToolbarTitle() {
        return "车辆轨迹";
    }

    @Override
    public void init() {
        mBaiDuMap = mMapView.getMap();
        mOrderModel = new OrderModel();

        requestVehicleTrajectory();

//        requestNativeVehicleTrajectory();


    }

    private void requestNativeVehicleTrajectory() {
        String result = ResourceUtils.readStringFromAssert("trajectory.json");
//        List<TrajectoryResultInfo> resultInfoList = JsonUtil.fromJson(JsonUtil.toJson(result), new TypeToken<List<TrajectoryResultInfo>>() {
        List<TrajectoryResultInfo> resultInfoList = JsonUtil.fromJson(result, new TypeToken<List<TrajectoryResultInfo>>() {
        }.getType());
        LogUtil.print(JsonUtil.toJson(resultInfoList));
        List<TrajectoryInfo> list = new ArrayList<>();
        if (resultInfoList != null && resultInfoList.size() > 0) {

            for (TrajectoryResultInfo resultInfo : resultInfoList) {
                List<TrajectoryInfo> resultList = JsonUtil.fromJson(resultInfo.result, new TypeToken<List<TrajectoryInfo>>() {
                }.getType());
                list.addAll(resultList);
            }

        }
        mBaiDuMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                showVehicleTrajectoryView(list);
            }
        });


//        String string = ResourceUtils.readStringFromAssert("vehicle_trajectory.json");
//        List<TrajectoryInfo> list = JsonUtil.fromJson(string, new TypeToken<List<TrajectoryInfo>>() {
//        }.getType());
//
//        mBaiDuMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
//            @Override
//            public void onMapLoaded() {
//                showVehicleTrajectoryView(list);
//            }
//        });
    }

    private void requestVehicleTrajectory() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            orderInfo = bundle.getParcelable(KeyValue.KEY_ORDER_INFO);
            if (orderInfo != null) {
                Map<String, String> map = new HashMap<>();
                String startDate = "";
                String endDate = "";
                if (orderInfo.isstate == 7) {
                    startDate = orderInfo.trantime;
                    endDate = DateUtil.getStandardTime(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
                } else if (orderInfo.isstate == 9 || orderInfo.isstate > 11) {
                    startDate = orderInfo.trantime;
                    endDate = orderInfo.recelvetime;
                }
//                else {
//                    return;
//                }

                map.put("dispatchno", orderInfo.dispatchno);
                map.put("vclN", orderInfo.vehiclenum);
                map.put("qryBtm", startDate);
                map.put("qryEtm", endDate);

//                map.put("dispatchno", "D20231114000000038");
//                map.put("vclN", "鲁ND5641");
//                map.put("qryBtm", "2023-11-14 16:28:06");
//                map.put("qryEtm", "2023-11-15 10:58:15");


                mOrderModel.vehicleTrajectoryModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
                    @Override
                    public void onNext(CommonResponse commonResponse) {
                        if (commonResponse.getCode() == 20000) {
                            List<TrajectoryResultInfo> resultInfoList = JsonUtil.fromJson(JsonUtil.toJson(commonResponse.getData()), new TypeToken<List<TrajectoryResultInfo>>() {
                            }.getType());
                            LogUtil.print(JsonUtil.toJson(resultInfoList));
                            if (resultInfoList != null && resultInfoList.size() > 0) {
                                List<TrajectoryInfo> list = new ArrayList<>();
                                for (TrajectoryResultInfo resultInfo : resultInfoList) {
                                    List<TrajectoryInfo> resultList = JsonUtil.fromJson(resultInfo.result, new TypeToken<List<TrajectoryInfo>>() {
                                    }.getType());
                                    list.addAll(resultList);
                                }
                                showVehicleTrajectoryView(list);

                            } else {
                                showToast("暂无运行轨迹");
                            }
                        } else {
                            showToast(commonResponse.getMsg());
                        }
                    }


                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        showToast(e.message);
                    }
                });


                //app轨迹
                mOrderModel.getAppTrajectory(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
                    @Override
                    public void onNext(CommonResponse commonResponse) {
                        if (commonResponse.getCode() == 20000) {
                            List<TrajectoryResultInfo> resultInfoList = JsonUtil.fromJson(JsonUtil.toJson(commonResponse.getData()), new TypeToken<List<TrajectoryResultInfo>>() {
                            }.getType());
                            LogUtil.print(JsonUtil.toJson(resultInfoList));
                            if (resultInfoList != null && resultInfoList.size() > 0) {
                                List<TrajectoryInfo> list = new ArrayList<>();
                                for (TrajectoryResultInfo resultInfo : resultInfoList) {
                                    List<TrajectoryInfo> resultList = JsonUtil.fromJson(resultInfo.result, new TypeToken<List<TrajectoryInfo>>() {
                                    }.getType());
                                    list.addAll(resultList);
                                }
                                showAppTrajectoryView(list);

                            } else {
                                showToast("暂无运行轨迹");
                            }
                        } else {
                            showToast(commonResponse.getMsg());
                        }
                    }


                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        showToast(e.message);
                    }
                });


                try {
                    if (null!=orderInfo.deliverlat&&null!=orderInfo.deliverlon&&
                            !TextUtils.isEmpty(orderInfo.deliverlat)&& !TextUtils.isEmpty(orderInfo.deliverlon)) {

                        String  zhuanglatstr = Transform.gcj02tobd09(StringUtils.toDouble(orderInfo.deliverlon), StringUtils.toDouble(orderInfo.deliverlat));
                        String[] zhuangSplit = zhuanglatstr.split(",");
                        LatLng zhuanglatLng=new LatLng(StringUtils.toDouble(zhuangSplit[1]),StringUtils.toDouble(zhuangSplit[0]));
                        //装车

                        MarkerOptions zhuangMarker = new MarkerOptions()
                                .position(zhuanglatLng)
                                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.guiji_zhuang));
                        mBaiDuMap.addOverlay(zhuangMarker);
                    }

                    if (null!=orderInfo.destinationlat&&null!=orderInfo.destinationlon&&
                            !TextUtils.isEmpty(orderInfo.destinationlat)&& !TextUtils.isEmpty(orderInfo.destinationlon)) {
                        String  zielatstr = Transform.gcj02tobd09(StringUtils.toDouble(orderInfo.destinationlon), StringUtils.toDouble(orderInfo.destinationlat));
                        String[] zieSplit = zielatstr.split(",");
                        LatLng zielatLng=new LatLng(StringUtils.toDouble(zieSplit[1]),StringUtils.toDouble(zieSplit[0]));
                        //卸车
                        MarkerOptions xieMarker = new MarkerOptions()
                                .position(zielatLng)
                                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.guiji_zie));
                        mBaiDuMap.addOverlay(xieMarker);
                    }
               }catch (Exception e){
                      LogUtil.print(e.toString());
               }


            }
        }
    }

    private void showVehicleTrajectoryView(List<TrajectoryInfo> list) {
        try {

                if (list != null && list.size() > 0) {
                    LatLng latLng;
                    List<LatLng> points = new ArrayList<>();
                    List<PointDateInfo> pointDateInfoList = new ArrayList();

                    int size = list.size();
                    TrajectoryInfo info;
                    PointDateInfo pointDateInfo;
                    MarkerOptions redPointMarker;
                    int index = getPointIndex(list);
                    for (int i = 0; i < size; i++) {
                        info = list.get(i);
                        double lat = StringUtils.toDouble(info.lat) / 600000;
                        double lng = StringUtils.toDouble(info.lon) / 600000;

                        latLng = Transform.wgs84tobd09(lng, lat);
                        points.add(latLng);

                        if (i % index == 0) {
                            pointDateInfo = new PointDateInfo();
                            pointDateInfo.latLng = latLng;
                            pointDateInfo.gtm = info.gtm;
                            pointDateInfoList.add(pointDateInfo);
                        }
                    }

                    //路线
                    OverlayOptions options = new PolylineOptions()
                            .width(10)
                            .color(getResources().getColor(R.color.colorGreen))
                            .points(points);
                    mBaiDuMap.addOverlay(options);


                    //起点
                    MarkerOptions startMarker = new MarkerOptions()
                            .position(points.get(0))
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.guiji_qi));
                    mBaiDuMap.addOverlay(startMarker);


//                    TrajectoryInfo info2 = list.get(0);
//                    double lat = StringUtils.toDouble(info2.lat) / 600000;
//                    double lng = StringUtils.toDouble(info2.lon) / 600000;
//
//                    LatLng sourceLatLng=new LatLng(lat,lng);
//                    CoordinateConverter converter  = new CoordinateConverter();
//                    // CoordType.GPS 待转换坐标类型
//                    converter.from(CoordinateConverter.CoordType.GPS);
//                    // sourceLatLng待转换坐标点 LatLng类型
//                    converter.coord(sourceLatLng);
//                    // 执行转换操作
//                    LatLng desLatLng = converter.convert();



                    mBaiDuMap.addOverlay(getTextOptions(list.get(0).gtm, points.get(0)));



                    mBaiDuMap.addOverlay(getTextOptions(list.get(points.size() - 1).gtm, points.get(points.size() - 1)));

                    //日期和圆点

                    if (pointDateInfoList != null && pointDateInfoList.size() > 0) {
                        int textPointSize = pointDateInfoList.size();
                        for (int i = 0; i < textPointSize; i++) {
                            redPointMarker = new MarkerOptions()
                                    .position(pointDateInfoList.get(i).latLng)
                                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_red_circle));
                            mBaiDuMap.addOverlay(redPointMarker);

                            mBaiDuMap.addOverlay(getTextOptions(pointDateInfoList.get(i).gtm, pointDateInfoList.get(i).latLng));
                        }

                    }
                    MapStatusUpdate mapStatusUpdate;
                    if (orderInfo != null && orderInfo.isstate >= 9) {
                        mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(points.get(points.size() / 2), 8);
                    } else {
                        mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(points.get(points.size() - 1), 10);
                    }
                    mBaiDuMap.setMapStatus(mapStatusUpdate);



                    int endImageId = R.mipmap.icon_vehicle_track_position;
                    if (orderInfo != null && orderInfo.isstate >= 9) {
                        endImageId = R.mipmap.guiji_zhong;
                    }

                    //终点
                    MarkerOptions endMarker = new MarkerOptions()
                            .position(points.get(points.size() - 1))
                            .icon(BitmapDescriptorFactory.fromResource(endImageId));
                    mBaiDuMap.addOverlay(endMarker);



//                    TrajectoryInfo info3 = list.get(points.size() - 1);
//                    double lat3 = StringUtils.toDouble(info3.lat) / 600000;
//                    double lng3 = StringUtils.toDouble(info3.lon) / 600000;
//
//                    LatLng sourceLatLng3=new LatLng(lat3,lng3);
//                    CoordinateConverter converter3  = new CoordinateConverter();
//                    // CoordType.GPS 待转换坐标类型
//                    converter3.from(CoordinateConverter.CoordType.GPS);
//                    // sourceLatLng待转换坐标点 LatLng类型
//                    converter3.coord(sourceLatLng3);
//                    // 执行转换操作
//                    LatLng desLatLng3 = converter3.convert();
//                    double latitude = desLatLng3.latitude;

//                    String s2 = Transform.wgs84togcj02(points.get(points.size() - 1).longitude/600000,points.get(points.size() - 1).latitude/600000);
//                    String s3=s2;
                } else {
                    showToast("暂无轨迹信息");
                }
         }catch (Exception e){
            ToastUtil.showShortToast("未找到司机轨迹信息");
        }
    }




    private void showAppTrajectoryView(List<TrajectoryInfo> list) {
        try {

            if (list != null && list.size() > 0) {
                LatLng latLng;
                List<LatLng> points = new ArrayList<>();
                List<PointDateInfo> pointDateInfoList = new ArrayList();

                int size = list.size();
                TrajectoryInfo info;
                PointDateInfo pointDateInfo;
                MarkerOptions redPointMarker;
                int index = getPointIndex(list);
                for (int i = 0; i < size; i++) {
                    info = list.get(i);
                    double lat = StringUtils.toDouble(info.lat) / 600000;
                    double lng = StringUtils.toDouble(info.lon) / 600000;

                    latLng = Transform.wgs84tobd09(lng, lat);
                    points.add(latLng);

                    if (i % index == 0) {
                        pointDateInfo = new PointDateInfo();
                        pointDateInfo.latLng = latLng;
                        pointDateInfo.gtm = info.gtm;
                        pointDateInfoList.add(pointDateInfo);
                    }
                }

                //路线
                OverlayOptions options = new PolylineOptions()
                        .width(10)
                        .color(getResources().getColor(R.color.colorBlue))
                        .points(points);
                mBaiDuMap.addOverlay(options);


                //起点
//                MarkerOptions startMarker = new MarkerOptions()
//                        .position(points.get(0))
//                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.guiji_qi));
//                mBaiDuMap.addOverlay(startMarker);

                mBaiDuMap.addOverlay(getTextOptions(list.get(0).gtm, points.get(0)));

//                int endImageId = R.mipmap.icon_vehicle_track_position;
//                if (orderInfo != null && orderInfo.isstate >= 9) {
//                    endImageId = R.mipmap.guiji_zhong;
//                }

                //终点
//                MarkerOptions endMarker = new MarkerOptions()
//                        .position(points.get(points.size() - 1))
//                        .icon(BitmapDescriptorFactory.fromResource(endImageId));
//                mBaiDuMap.addOverlay(endMarker);

                mBaiDuMap.addOverlay(getTextOptions(list.get(points.size() - 1).gtm, points.get(points.size() - 1)));

                //日期和圆点
                if (pointDateInfoList != null && pointDateInfoList.size() > 0) {
                    int textPointSize = pointDateInfoList.size();
                    for (int i = 0; i < textPointSize; i++) {
                        redPointMarker = new MarkerOptions()
                                .position(pointDateInfoList.get(i).latLng)
                                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_red_circle));
                        mBaiDuMap.addOverlay(redPointMarker);

                        mBaiDuMap.addOverlay(getTextOptions(pointDateInfoList.get(i).gtm, pointDateInfoList.get(i).latLng));
                    }

                }
                MapStatusUpdate mapStatusUpdate;
                if (orderInfo != null && orderInfo.isstate >= 9) {
                    mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(points.get(points.size() / 2), 8);
                } else {
                    mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(points.get(points.size() - 1), 10);
                }
                mBaiDuMap.setMapStatus(mapStatusUpdate);

            } else {
                showToast("暂无轨迹信息");
            }
        }catch (Exception e){
            ToastUtil.showShortToast("未找到司机轨迹信息");
        }
    }




    private TextOptions getTextOptions(String time, LatLng latLng) {
        return new TextOptions()
                .fontColor(getResources().getColor(R.color.colorBlue))
                .fontSize(20)
//                .rotate(-30)
                .text(DateUtil.getDateStringFormat(time, "yyyyMMdd/HHmmss", "yyyy-MM-dd HH:mm:ss"))
                .position(latLng);
    }

    private int getPointIndex(List<TrajectoryInfo> list) {
        int result = 1;
        int size = list.size();
        if (size > 50) {
            result = size / 50;
        }

        return result;
    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    @Override
    protected void onResume() {
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }








}
